package nancal.mp.mvc.ops

import nancal.mp.db.mongo.entity.dev.JenkinsLogItemData
import nancal.mp.db.mongo.entity.dev.JenkinsOpsLog
import nancal.mp.db.mongo.extend.getAppDeploySetting
import nancal.mp.db.mongo.mor
import nancal.mp.service.jenkins.JenkinsExportModel
import nancal.mp.service.jenkins.JenkinsService
import nancal.mp.service.jenkins.ops.getK8sOpsFiles
import nancal.mp.util.JenkinsUtil
import nbcp.base.annotation.log.MyLogLevel
import nbcp.base.annotation.mvc.AdminSysOpsAction
import nbcp.base.annotation.mvc.OpenAction
import nbcp.base.comm.ApiResult
import nbcp.base.comm.ListResult
import nbcp.base.db.IdValue
import nbcp.base.db.LoginUserModel
import nbcp.base.enums.LogLevelScopeEnum
import nbcp.base.extend.AsBoolean
import nbcp.base.extend.AsString
import nbcp.base.extend.must
import nbcp.base.utils.CodeUtil
import nbcp.base.utils.FileUtil
import nbcp.base.utils.ZipUtil
import nbcp.mvc.sys.setDownloadFileName
import nbcp.myoql.db.mongo.query
import nbcp.myoql.db.mongo.queryById
import nbcp.myoql.db.mongo.updateById
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.io.File
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 导入导出
 */
@RequestMapping("/ops/jenkins-ops")
@RestController
@AdminSysOpsAction
class JenkinsExportOpsController {
    companion object {
        private val logger = LoggerFactory.getLogger(this::class.java.declaringClass)
    }

    @Autowired
    lateinit var jenkinsService: JenkinsService;


    /**
     * 构建Jenkins任务
     */
    @PostMapping("/export-job")
    fun exportJob(
            @org.springframework.web.bind.annotation.RequestBody query: JenkinsOpsLog,
            loginUser: LoginUserModel
    ): ApiResult<IdValue> {

        var deploySetting = mor.dev.appDeploySetting.getAppDeploySetting(query.targetEnv);

        mor.dev.jenkinsOpsLog.doInsert(query);

        var jenkinsResult = jenkinsService.buildOpsExportJob(
                deploySetting.jenkinsServer.jenkinsHttpUrl,
                deploySetting.jenkinsServer.userName,
                deploySetting.jenkinsServer.password,
                JenkinsExportModel.loadFrom(query),
                deploySetting.jenkinsServer.usePipeline
        )

        if (jenkinsResult.hasError) {
            return ApiResult.error(jenkinsResult.msg);
        }
        query.buildNumber = jenkinsResult.data ?: 0;
        mor.dev.jenkinsOpsLog.updateById(query.id)
                .set { it.buildNumber to query.buildNumber }
                .exec();

        return ApiResult.of(IdValue(query.id, query.buildNumber.toString()))
    }


    @GetMapping("/cmd/file/{id}")
    fun get_cmd_file(id: String, response: HttpServletResponse) {
        var file =
                File(
                        FileUtil.resolvePath(
                                System.getProperty("java.io.tmpdir"),
                                "jenkins-ops-cmd-${CodeUtil.getCode()}.zip"
                        )
                )

        var log = mor.dev.jenkinsOpsLog.queryById(id).toEntity()
                .must()
                .elseThrow { "找不到记录" };

        try {
            var zip = ZipUtil.beginCompress(file)
            JenkinsExportModel.loadFrom(log).getK8sOpsFiles()
                    .forEach {
                        if (it.bytes.any()) {
                            zip.addFile(it.bytes.inputStream(), it.fileName)
                        }
                    }

            response.outputStream.write(file.readBytes())
            response.setDownloadFileName("jenkins-ops-cmd.zip")
        } finally {
            file.deleteOnExit()
        }
    }


    @MyLogLevel(LogLevelScopeEnum.ERROR)
    @PostMapping("/last-log")
    fun last_tasks(
            targetEnv: String,
            lastStage: Boolean?,
            request: HttpServletRequest
    ): ListResult<JenkinsLogItemData> {
        var deploySetting = mor.dev.appDeploySetting.getAppDeploySetting(targetEnv);

        var dbLog = mor.dev.jenkinsOpsLog.query()
                .orderByDesc { it.id }
                .toEntity();

        if (dbLog == null) {
            return ListResult.error("还没有导出过！");
        }

        var jenkinsLog = jenkinsService.getLog(
                deploySetting.jenkinsServer.jenkinsHttpUrl,
                deploySetting.jenkinsServer.userName,
                deploySetting.jenkinsServer.password,
                "k8s-ops-export",
                0
        )

        if (jenkinsLog == null) {
            return ListResult.of(listOf<JenkinsLogItemData>()).withValue(false)
        }

        var ret = JenkinsUtil.analyse(jenkinsLog.data?.content.AsString())

        if (lastStage != null && lastStage) {
            ret.data = listOf(ret.data.last());
        }

        if (jenkinsLog.value != null) {
            if (jenkinsLog.value.AsBoolean()) {
                return ListResult.of(ret.data).withValue(true)
            } else {
                return ListResult.of(ret.data).withValue(false)
            }
        } else {
            return ListResult.of(ret.data);
        }
    }
}
